const dataSource = require('./dataSource');
const logger     = require('../util/log');
const config     = require('../crawler/config/config');
const Const      = require('../common/const');

const _TABLE_NAMES = {
    _long_video:'long_video',
    _prohub_cates:'prohub_cates'
};

class Crud {

    /**
     * 写入数据
     */
    static async saveTask(tasks){
        let sql = `INSERT INTO ${_TABLE_NAMES._long_video} (title,source_url,thumbnail,duration,hd,author,views,media_book,like_cnt,task_id,create_time,status,cate_id,cate_name) VALUES ?`;
        let params = [];
        tasks.forEach(task => {
            let param = [];
            param.push(task.title);
            param.push(task.href);
            param.push(task.thumbnail);
            param.push(task.duration);
            param.push(task.hd);
            param.push(task.author);
            param.push(task.views);
            param.push(task.mediaBook);
            param.push(task.likeCnt);
            param.push(task.taskId);
            param.push(new Date());
            param.push(task.status);
            param.push(task.cateId);
            param.push(task.cateName);
            params.push(param);
        });
        await new dataSource().execute(sql,[params]);
    }

    /**
     * 保存类目
     */
    static async saveCate(cates,parentId){
        let sql = `INSERT INTO ${_TABLE_NAMES._prohub_cates} (cate_name,img,href,count,parent_id) VALUES ?`;
        let params = [];
        cates.forEach(item => {
            let param = [];
            param.push(item.cateName);
            param.push(item.img);
            param.push(item.href);
            param.push(item.count);
            param.push(parentId); //父类目ID PronHub
            params.push(param);
        });
        await new dataSource().execute(sql,[params]);
    }

    /**
     * 查询所有类目
     */
    static async queryAllCates(){
        let sql = `SELECT * FROM ${_TABLE_NAMES._prohub_cates}`;
        return await new dataSource().execute(sql);
    }

    /**
     * 清空表
     * @param tableName 表名
     */
    static async truncateTable(tableName){
        let sql = `truncate table ${tableName}`;
        await new dataSource().execute(sql);
    }

    /**
     * 更新任务下载状态
     */
    static async updateTaskStatusOnFinish(taskId, status){
        let sql = `UPDATE ${_TABLE_NAMES._long_video} SET status = ${status},play_url='${config.ASSEMBLY.URL_PREFIX}${taskId}.mp4' WHERE task_id = '${taskId}'`;
        await new dataSource().execute(sql);
    }

    /**
     * 删除一个任务
     * @returns {Promise<void>}
     */
    static async deleteByTaskId(taskId){
        let sql = `DELETE FROM ${_TABLE_NAMES._long_video} WHERE task_id='${taskId}'`;
        await new dataSource().execute(sql);
    }

    /**
     * 获取下载完毕的影片总量
     */
    static async getDownloadFinishCount(status){
        let filterStr = `(${status}`;
        if(status == Const._TASK_STATUS._FINISH){
            filterStr += ',';
            filterStr += Const._TASK_STATUS._PUSH_FINISH;
        }
        filterStr += ')';
        let sql = `SELECT COUNT(*) AS count FROM ${_TABLE_NAMES._long_video} WHERE status IN ${filterStr}`;
        let result = await new dataSource().execute(sql);
        if(!result || result.length === 0){
            return 0;
        }
        return result[0].count;
    }

}

module.exports = Crud;
